import json
users={}
books=[]
borrow_records={}
def load_data():
    global users, books, borrow_records
    with open('Information.txt', 'r', encoding='utf-8') as f:
        data = json.load(f)
        users=data['users']
        books=data['books']
        borrow_records=data['borrow_records']

def save_data():
    with open('Information.txt', 'w', encoding='utf-8') as f:
        data = {
            'users': users,
            'books': books,
            'borrow_records': borrow_records
        }
        json.dump(data, f, ensure_ascii=False, indent=4)
        print('数据保存成功！')
def login():
    print('欢迎使用图书管理系统')
    while True:
        userName=input('请输入你的用户名')
        userKey=input('请输入你的密码')
        if userName in users and userKey==users[userName]:
            print('登陆成功')
            return userName
        else:
            print('用户名或密码错误')

#修改密码
def change_password(username):
    temp_password=input('请输入新密码')
    users[username]=temp_password

#借书
def borrow_book(username):
    print('可以借的书有:')
    for book in books:
        print(book)
    borrow_book_name=input('请输入要借阅的图书名称')
    if borrow_book_name in books:
        books.remove(borrow_book_name)
        borrow_records[username].append(borrow_book_name)
        print('借阅成功')
    else:
        print('没有此书')


def return_book(username):
    print('可以归还的书有:')
    print(borrow_records[username])
    return_book_name=input('请输入需要归还的图书名称')
    if return_book_name in borrow_records[username]:
        borrow_records[username].remove(return_book_name)
        books.append(return_book_name)
        print('归还成功')
    else:
        print('没有此书')

def chek_book(username):
    print('已借阅的书有:')
    print(borrow_records[username])
def main():
    load_data()
    username=login()
    while True:
        print(f'欢迎用户{username}')
        print('请选择操作')
        print('1. 修改密码')
        print('2. 借书')
        print('3. 还书')
        print('4. 查询已借阅的图书')
        print('5. 退出系统')

        choice=input('请输入你的选择(请输入纯数字)')
        if choice=='1':
            change_password(username)
            print('修改密码成功')
        elif choice=='2':
            borrow_book(username)
        elif choice=='3':
            return_book(username)
        elif choice=='4':
            chek_book(username)
        elif choice=='5':
            save_data()
            print('退出系统')

            break


if __name__ == '__main__':
    main()
